package main

import (
	"encoding/csv"
	"fmt"
	"github.com/flaravel/quanlaolao/app/models/channel"
	"github.com/flaravel/quanlaolao/bootstrap"
	"github.com/flaravel/quanlaolao/config"
	"github.com/flaravel/quanlaolao/pkg/model"
	"github.com/flaravel/quanlaolao/pkg/types"
	"math"
	"os"
	"sync"
)


func init() {
	// 初始化配置信息
	config.Initialize()
}

func ss() {
	// 链接数据库
	bootstrap.SetupDB()
	// 导出
	importCsv()
}



var wg sync.WaitGroup

func importCsv()  {
	file, err := os.OpenFile("test.csv", os.O_CREATE|os.O_RDWR, 0644)
	if err != nil {
		fmt.Println("open file is failed, err: ", err)
	}
	defer file.Close()
	file.WriteString("\xEF\xBB\xBF")
	w := csv.NewWriter(file)
	w.Write([]string{"组织ID", "组织名称"})

	// 总数
	var total int64

	// 每一页数量
	var pageSize int64

	var i int

	pageSize = 10000

	model.DB.Model(&channel.Channel{}).Count(&total)

	// 总页数量
	page := int(math.Ceil(float64(total / pageSize)))

	if page == 0 {
		page = 1
	}

	fmt.Println("channel count", page)

	wg.Add(page)

	for i = 1; i <= page; i++ {
		channel := []channel.Channel{}
		go export(i,pageSize,w,channel)
	}
	wg.Wait()
	fmt.Println("Done!")
}

func export(i int, pageSize int64,w *csv.Writer,channels []channel.Channel)  {
	offset := (int64(i) - 1) * pageSize
	model.DB.Model(&channel.Channel{}).Limit(int(pageSize)).Offset(int(offset)).Find(&channels)
	for _,ch := range channels{
		w.Write([]string{types.Int64ToString(int64(ch.ID)),ch.Name})
	}
	fmt.Println("当前页:",i)
	w.Flush()
	wg.Done()
}